<template>
  <div class="app-container">
    <el-row :gutter="32" class="equal-height-row">
      <!-- 左侧主内容区 -->
      <el-col :span="12" class="equal-height-col">
        <div class="main-content fill-height">
          <!-- logo区域 -->
          <div class="logo-box" v-if="leftLogoStatus === 1">
            <img :src="leftLogo" alt="logo" class="logo-img" />
          </div>
          <!-- 背景图区域 -->
          <div class="background-box" v-if="leftBackground">
            <img
              :src="leftBackground"
              alt="background"
              class="background-img"
            />
          </div>
          <!-- 轮播图区域 -->
          <div class="carousel-section">
            <el-carousel
              :interval="4000"
              type="card"
              height="280px"
              :autoplay="false"
              indicator-position="outside"
            >
              <el-carousel-item v-for="item in carouselColumns" :key="item.id">
                <div class="carousel-card">
                  <img :src="item.backgroundImage" class="card-img" />
                  <div class="card-title">{{ item.columnName }}</div>
                </div>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
        <!-- 表单卡片 -->
        <div class="sidebar-section sidebar-section-form">
          <div class="upload-container">
            <!-- Logo上传区域 -->
            <div class="upload-section">
              <div class="upload-title">Logo</div>
              <div class="logo-upload-center">
                <div class="button-group">
                  <el-upload
                    class="logo-uploader"
                    :show-file-list="false"
                    :http-request="handleLogoChange"
                  >
                    <img
                      v-if="form.logo"
                      :src="form.logo"
                      class="logo-preview1"
                    />
                    <el-button v-else class="upload-btn">上传Logo</el-button>
                  </el-upload>
                  <el-button
                    type="primary"
                    @click="submitLogo"
                    class="upload-btn"
                    :disabled="!form.logo"
                  >
                    确定Logo
                  </el-button>
                  <el-button
                    type="primary"
                    class="upload-btn"
                    @click="toggleLogoStatus"
                  >
                    {{ form.logoStatus === 1 ? "隐藏Logo" : "显示Logo" }}
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 背景图上传区域 -->
            <div class="upload-section">
              <div class="upload-title">背景图</div>
              <div class="logo-upload-center">
                <div class="button-group">
                  <el-upload
                    class="logo-uploader"
                    :show-file-list="false"
                    :http-request="handleBackgroundChange"
                  >
                    <img
                      v-if="form.backgroundImage"
                      :src="form.backgroundImage"
                      class="logo-preview2"
                    />
                    <el-button v-else class="upload-btn">上传背景图</el-button>
                  </el-upload>
                  <el-button
                    type="primary"
                    @click="submitBackground"
                    class="upload-btn"
                    :disabled="!form.backgroundImage"
                  >
                    确定背景图
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 表单卡片 -->
        <div class="sidebar-section sidebar-section-form">
          <div class="upload-container">
            <!-- 背景图上传区域 -->
            <div class="upload-section">
              <el-button
                class="upload-btn"
                @click="openAppTableDialog({ id: 5 })"
                >工具</el-button
              >
            </div>
          </div>
        </div>
      </el-col>
      <!-- 右侧侧边栏 -->
      <el-col :span="12" class="equal-height-col">
        <div class="sidebar sidebar-card fill-height">
          <!-- 表格卡片 -->
          <div class="sidebar-section sidebar-section-table">
            <div class="table-header-row">
              <div class="table-header-title">栏目</div>
              <el-button type="primary" @click="handleAdd" class="add-btn"
                >新增</el-button
              >
            </div>
            <div class="table-container">
              <el-table
                :data="tableData"
                class="sidebar-table"
                border
                stripe
                style="width: 100%; height: 100%"
              >
                <el-table-column prop="id" label="ID" align="center" />
                <el-table-column
                  prop="columnName"
                  label="栏目名"
                  width="100"
                  align="center"
                />
                <el-table-column label="图片" align="center" width="100">
                  <template #default="scope">
                    <img :src="scope.row.backgroundImage" class="table-img" />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="visible"
                  label="显示"
                  width="80"
                  align="center"
                >
                  <template #default="scope">
                    <el-switch
                      :disabled="scope.row.isUploadApp === 0"
                      :model-value="scope.row.status === 1"
                      @change="(val) => handleStatusChange(scope.row, val)"
                    ></el-switch>
                  </template>
                </el-table-column>
                <!-- 新增：模式列 -->
                <el-table-column
                  prop="modeType"
                  label="模式"
                  width="100"
                  align="center"
                >
                  <template #default="scope">
                    <span>{{ modeTypeText(scope.row.modeType) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="300">
                  <template #default="scope">
                    <el-button
                      type="success"
                      plain
                      @click="openAppTableDialog(scope.row)"
                      v-hasPermi="['deviceBox:boxinfo:add']"
                      >查看应用</el-button
                    >
                    <el-button
                      type="success"
                      plain
                      @click="handleEdit(scope.row)"
                      v-hasPermi="['deviceBox:boxinfo:add']"
                      >编辑</el-button
                    >
                    <el-button
                      type="success"
                      plain
                      @click="handleDeleteColumn(scope.row)"
                      v-hasPermi="['deviceBox:boxinfo:add']"
                      v-if="scope.row.isUploadApp === 1"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 新增：应用信息弹窗表单 -->
    <el-dialog
      v-model="appDialogVisible"
      :title="appDialogTitle"
      width="90%"
      :z-index="9999"
      append-to-body
      :modal-append-to-body="false"
    >
      <el-form :model="appForm" label-width="110px">
        <el-form-item label="APK文件上传">
          <el-upload
            class="apk-uploader"
            action="#"
            :show-file-list="false"
            :http-request="customAppApkUploadRequest"
            accept=".apk"
          >
            <el-button type="primary">上传APK</el-button>
          </el-upload>
          <div
            v-if="appForm.url"
            style="margin-top: 8px; color: #666; font-size: 13px"
          >
            已上传: {{ appForm.url }}
          </div>
        </el-form-item>
        <el-form-item label="栏目" v-if="appForm.columnId !== 5">
          <el-select
            v-model="appForm.columnId"
            placeholder="请选择"
            clearable
            :disabled="appForm.isDefault === 1"
            popper-class="app-select-dropdown"
            style="width: 120px"
            @change="handleColumnChange"
          >
            <el-option
              :label="item.columnName"
              :value="Number(item.id)"
              v-for="(item, index) in columnList"
              :key="item.id || index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="appForm.orderNum" />
        </el-form-item>
        <el-form-item label="应用名称">
          <el-input v-model="appForm.name" />
        </el-form-item>
        <el-form-item label="包名">
          <el-input v-model="appForm.packageName" />
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="appForm.versionCode" />
        </el-form-item>
        <el-form-item label="版本名称">
          <el-input v-model="appForm.versionName" />
        </el-form-item>
        <el-form-item label="文件大小">
          <el-input v-model="appForm.size" />
        </el-form-item>

        <el-form-item label="应用图标路径">
          <el-input v-model="appForm.icon" />
        </el-form-item>

        <el-form-item label="是否为公共应用">
          <el-switch
            v-model="appForm.isCommon"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
            :disabled="appForm.columnId == '10'"
          />
        </el-form-item>

        <el-form-item label="APK文件路径">
          <el-input v-model="appForm.url" readonly />
        </el-form-item>
        <!-- <el-form-item label="默认应用">
          <el-switch
            v-model="appForm.isDefault"
            :active-value="1"
            :inactive-value="0"
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="appDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApp">确定</el-button>
      </template>
    </el-dialog>
    <!-- 应用信息表格弹窗 -->
    <el-dialog v-model="appTableDialogVisible" title="应用信息" width="90%">
      <div class="table-header-row">
        <div class="table-header-title">应用信息</div>
        <el-button
          type="primary"
          @click="openAppDialog(currentColumnId)"
          class="add-btn"
          >新增</el-button
        >
      </div>
      <el-table
        :data="appTableData"
        border
        stripe
        style="width: 100%; height: 70vh"
      >
        <el-table-column label="图标" align="center">
          <template #default="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.icon"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="应用名称" align="center" />
        <el-table-column prop="packageName" label="包名" align="center" />
        <el-table-column prop="versionCode" label="版本号" align="center" />
        <el-table-column prop="versionName" label="版本名称" align="center" />
        <el-table-column prop="url" label="apk" align="center" />
        <el-table-column label="默认状态" align="center" width="120">
          <template #default="scope">
            <el-tag
              :type="scope.row.isDefault === 1 ? 'success' : 'info'"
              size="small"
            >
              {{ scope.row.isDefault === 1 ? "默认应用" : "普通应用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="文件大小" align="center">
          <template #default="scope">
            <span>{{ formatSize(scope.row.size) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isCommon" label="公共应用" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isCommon"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
              @change="handleIsCommonChange(scope.row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="300">
          <template #default="scope">
            <el-button
              type="success"
              plain
              @click="editApp(scope.row)"
              v-hasPermi="['deviceBox:boxinfo:add']"
              >编辑</el-button
            >
            <el-button
              type="success"
              plain
              @click="handleDeleteApp(scope.row)"
              v-hasPermi="['deviceBox:boxinfo:add']"
              >删除</el-button
            >
            <el-button
              :type="scope.row.isDefault === 1 ? 'primary' : 'success'"
              plain
              @click="handleSetDefault(scope.row)"
              v-hasPermi="['deviceBox:boxinfo:add']"
              >{{
                scope.row.isDefault === 1 ? "设为默认" : "设为默认"
              }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 新增栏目弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="isEdit ? '编辑栏目' : '新增栏目'"
      width="60%"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="栏目名" prop="columnName">
          <el-input v-model="addForm.columnName" />
        </el-form-item>

        <el-form-item label="栏目图片">
          <el-upload
            ref="addUploadRef"
            :http-request="customAddUploadRequest"
            list-type="picture-card"
            :show-file-list="true"
            :auto-upload="true"
            :limit="1"
            accept="image/*"
            v-model:file-list="addUploadFileList"
            :on-remove="handleAddImageRemove"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip text-red">
                建议尺寸357*130像素，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示">
          <el-switch
            :disabled="addForm.isUploadApp === 0"
            v-model="addForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="addForm.orderNum" />
        </el-form-item>
        <el-form-item label="模式" prop="modeType">
          <el-select
            v-model="addForm.modeType"
            placeholder="请选择模式"
            style="width: 240px"
          >
            <el-option
              v-for="item in mode_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitColumn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import {
  listColumnInfo,
  addColumnInfo,
  uploadColumnImage,
  deleteColumnInfo,
  updateColumnInfo,
  getAppInfoByColumnId,
  uploadAppApk,
  addAppInfo,
  getMainScreenImageData,
  updateMainScreenImageData,
} from "@/api/deviceBox/column";
import {
  delBoxapp,
  updateDefaultApp,
  updateBoxapp,
} from "@/api/deviceBox/boxapp";
import { upload as uploadImage } from "@/api/portal/banner";
import { ElMessageBox, ElMessage, ElLoading } from "element-plus";
const { proxy } = getCurrentInstance();
const { mode_type } = proxy.useDict("mode_type");
const form = ref({
  logo: "",
  backgroundImage: "",
  logoStatus: 1, // 新增，默认显示
});
const leftLogo = ref("");
const leftBackground = ref("");
const leftLogoStatus = ref(1); // 新增

const tableData = ref([]);
const columnList = ref([]);
onMounted(async () => {
  await fetchLeftLogo();
  try {
    const res = await listColumnInfo();
    tableData.value = res?.rows || res.data || [];
    // 过滤掉 columnName 为 "全部应用" 的项
    columnList.value = res?.rows || res.data || [];
    console.log("columnList", columnList.value);
  } catch (e) {
    tableData.value = [];
    columnList.value = [];
  }
});
async function handleIsCommonChange(row) {
  await updateBoxapp(row);
  ElMessage.success("应用更新成功");
}

async function fetchLeftLogo() {
  try {
    const res = await getMainScreenImageData();
    leftLogo.value = res.data.logoImage || "";
    leftBackground.value = res.data.backgroundImage || "";
    leftLogoStatus.value = res.data.logoStatus ?? 1; // 新增
    form.value.logoStatus = res.data.logoStatus ?? 1; // 新增
  } catch (e) {
    leftLogo.value = "";
    leftBackground.value = "";
    leftLogoStatus.value = 1;
    form.value.logoStatus = 1;
  }
}

async function handleLogoChange(option) {
  // 显示上传Loading
  const loading = ElLoading.service({
    lock: true,
    text: "Logo上传中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });

  // 上传到服务器，拿到图片地址
  const formData = new FormData();
  formData.append("file", option.file);
  try {
    const res = await uploadColumnImage(formData);
    form.value.logo = res.fileUrl || res.data?.fileUrl || "";
    option.onSuccess && option.onSuccess(res, option.file);
    ElMessage.success("Logo上传成功");
  } catch (e) {
    ElMessage.error("Logo上传失败");
    option.onError && option.onError(e);
  } finally {
    loading.close();
  }
}

async function handleBackgroundChange(option) {
  // 显示上传Loading
  const loading = ElLoading.service({
    lock: true,
    text: "背景图上传中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });

  // 上传到服务器，拿到图片地址
  const formData = new FormData();
  formData.append("file", option.file);
  try {
    const res = await uploadColumnImage(formData);
    form.value.backgroundImage = res.fileUrl || res.data?.fileUrl || "";
    option.onSuccess && option.onSuccess(res, option.file);
    ElMessage.success("背景图上传成功");
  } catch (e) {
    ElMessage.error("背景图上传失败");
    option.onError && option.onError(e);
  } finally {
    loading.close();
  }
}

async function submitLogo() {
  // 判断是否有logo
  if (!form.value.logo) {
    ElMessage.warning("请先上传Logo");
    return;
  }
  // 显示提交Loading
  const loading = ElLoading.service({
    lock: true,
    text: "Logo更新中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });
  // 调用接口修改logo
  try {
    await updateMainScreenImageData({
      logoImage: form.value.logo,
      logoStatus: form.value.logoStatus,
      id: 1,
    });
    ElMessage.success("Logo更新成功");
    // 刷新左侧logo
    await fetchLeftLogo();
    form.value.logo = "";
  } catch (e) {
    ElMessage.error("Logo更新失败");
  } finally {
    loading.close();
  }
}

async function submitLogoStatus() {
  const loading = ElLoading.service({
    lock: true,
    text: "Logo显示状态更新中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });
  try {
    await updateMainScreenImageData({
      logoStatus: form.value.logoStatus,
      id: 1,
    });
    ElMessage.success("Logo显示状态更新成功");
    await fetchLeftLogo();
  } catch (e) {
    ElMessage.error("Logo显示状态更新失败");
  } finally {
    loading.close();
  }
}

async function submitBackground() {
  // 判断是否有背景图
  if (!form.value.backgroundImage) {
    ElMessage.warning("请先上传背景图");
    return;
  }

  // 显示提交Loading
  const loading = ElLoading.service({
    lock: true,
    text: "背景图更新中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });

  // 调用接口修改背景图
  try {
    await updateMainScreenImageData({
      backgroundImage: form.value.backgroundImage,
      id: 1,
    });
    ElMessage.success("背景图更新成功");
    // 刷新左侧背景图
    await fetchLeftLogo();
    form.value.backgroundImage = "";
  } catch (e) {
    ElMessage.error("背景图更新失败");
  } finally {
    loading.close();
  }
}

// 新增：应用信息表格相关逻辑
const appTableData = ref([]);
const appDialogVisible = ref(false);
const appDialogTitle = ref("");
const appForm = reactive({
  label: "",
  packageName: "",
  orderNum: "",
  versionCode: "",
  versionName: "",
  minsdkVersion: "",
  targetSdkVersion: "",
  icon: "",
  size: "",
  iconFullPath: "",
  url: "",
  columnId: "",
  isDefault: 0,
  isCommon: 0,
});
let appEditIndex = -1;
let currentColumnId = null;

function openAppDialog(columnId) {
  appDialogTitle.value = "新增应用";
  Object.assign(appForm, {
    name: "",
    label: "",
    packageName: "",
    orderNum: "",
    versionCode: "",
    versionName: "",
    size: "",
    minsdkVersion: "",
    targetSdkVersion: "",
    icon: "",
    iconFullPath: "",
    url: "",
    columnId: columnId || currentColumnId,
    isDefault: 0,
    isCommon: 0,
    id: "",
  });
  console.log("appForm", appForm);

  appEditIndex = -1;
  appDialogVisible.value = true;
}
function editApp(row, idx) {
  appDialogTitle.value = "编辑应用";
  Object.assign(appForm, {
    name: row.name,
    packageName: row.packageName,
    orderNum: row.orderNum,
    versionCode: row.versionCode,
    versionName: row.versionName,
    size: row.size,
    minsdkVersion: row.minsdkVersion,
    targetSdkVersion: row.targetSdkVersion,
    icon: row.icon,
    iconFullPath: row.fullIconPath,
    url: row.url,
    columnId: row.columnId || currentColumnId,
    isDefault: row.isDefault || 0,
    isCommon: row.isCommon || 0,
    id: row.id,
  });
  appEditIndex = idx;
  appDialogVisible.value = true;
}
async function submitApp() {
  // 显示提交Loading
  const loading = ElLoading.service({
    lock: true,
    text: appForm.id ? "应用更新中..." : "应用创建中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });

  try {
    let option = {
      ...appForm,
    };
    if (Number(appForm.columnId) === 5 || Number(currentColumnId) === 5) {
      option.type = 5;
      // 删除 columnId 键
      delete option.columnId;
    } else {
      option.columnId = appForm.columnId || currentColumnId;
    }
    if (appForm.id) {
      await updateBoxapp(option);
      ElMessage.success("应用更新成功");
    } else {
      await addAppInfo(option);
      ElMessage.success("应用创建成功");
    }

    appDialogVisible.value = false;
    // 刷新应用列表
    await getAppInfoList(appForm.columnId || currentColumnId);
  } catch (e) {
    ElMessage.error(appForm.id ? "应用更新失败" : "应用创建失败");
  } finally {
    loading.close();
  }
}
function deleteApp(idx) {
  appTableData.value.splice(idx, 1);
}

const appTableDialogVisible = ref(false);
async function getAppInfoList(columnId) {
  try {
    let option = {};
    if (Number(columnId) === 5) {
      option.type = 5;
    } else {
      option.columnId = columnId;
    }
    const res = await getAppInfoByColumnId(option);
    appTableData.value = res?.rows || res.data || [];
  } catch (e) {
    appTableData.value = [];
  }
}
function openAppTableDialog(row) {
  currentColumnId = Number(row.id);
  getAppInfoList(row.id);
  appTableDialogVisible.value = true;
}

// 新增栏目逻辑
const addDialogVisible = ref(false);
const isEdit = ref(false); // 是否编辑模式
const editId = ref(null); // 编辑的栏目id
const addForm = reactive({
  columnName: "",
  backgroundImage: "",
  status: 1, // 1显示，0不显示
  orderNum: "",
  isUploadApp: "",
  modeType: mode_type.length > 0 ? mode_type[0].dictValue : "",
});
const addFormRules = {
  columnName: [{ required: true, message: "请输入栏目名", trigger: "blur" }],
  modeType: [{ required: true, message: "请选择模式", trigger: "change" }],
};
const addFormRef = ref(null);
const addUploadFileList = ref([]);
const addUploadRef = ref(null);

const customAddUploadRequest = async (option) => {
  // 显示上传Loading
  const loading = ElLoading.service({
    lock: true,
    text: "栏目图片上传中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });

  let formData = new FormData();
  formData.append("file", option.file);
  try {
    const res = await uploadColumnImage(formData);
    addForm.backgroundImage = res.fileUrl || res.data?.fileUrl || "";
    addUploadFileList.value = [
      { url: addForm.backgroundImage, uid: option.file.uid },
    ];
    option.onSuccess(res, option.file);
    ElMessage.success("栏目图片上传成功");
  } catch (e) {
    console.log(e);
    ElMessage.error("栏目图片上传失败");
    option.onError();
  } finally {
    loading.close();
  }
};
function handleAdd() {
  addDialogVisible.value = true;
  isEdit.value = false;
  editId.value = null;
  addForm.columnName = "";
  addForm.backgroundImage = "";
  addForm.status = 1;
  addForm.orderNum = "";
  addForm.isUploadApp = "";
  addForm.modeType = mode_type.length > 0 ? mode_type[0].dictValue : "";
  addUploadFileList.value = [];
}
function handleEdit(row) {
  addDialogVisible.value = true;
  isEdit.value = true;
  editId.value = row.id;
  addForm.columnName = row.columnName;
  addForm.backgroundImage = row.backgroundImage;
  addForm.status = row.status;
  addForm.orderNum = row.orderNum;
  addForm.isUploadApp = row.isUploadApp;
  addForm.modeType =
    row.modeType + "" || (mode_type.length > 0 ? mode_type[0].dictValue : "");
  // 图片回显
  addUploadFileList.value = row.backgroundImage
    ? [{ url: row.backgroundImage, uid: row.id }]
    : [];
}
async function submitColumn() {
  addFormRef.value.validate(async (valid) => {
    if (!valid) return;
    // 显示提交Loading
    const loading = ElLoading.service({
      lock: true,
      text: isEdit.value ? "栏目更新中..." : "栏目创建中...",
      background: "rgba(0, 0, 0, 0.7)",
      zIndex: 9999,
    });
    try {
      if (isEdit.value) {
        await updateColumnInfo({
          id: editId.value,
          columnName: addForm.columnName,
          backgroundImage: addForm.backgroundImage,
          status: addForm.status,
          modeType: addForm.modeType,
          orderNum: addForm.orderNum,
        });
        ElMessage.success("栏目更新成功");
      } else {
        await addColumnInfo({
          columnName: addForm.columnName,
          backgroundImage: addForm.backgroundImage,
          status: addForm.status,
          modeType: addForm.modeType,
          orderNum: addForm.orderNum,
        });
        ElMessage.success("栏目创建成功");
      }
      addDialogVisible.value = false;
      // 刷新栏目列表
      const res = await listColumnInfo();
      tableData.value = res?.rows || res.data || [];
      // 同时更新 columnList，并过滤掉 "全部应用"
      columnList.value = (res?.rows || res.data || []).filter(
        (item) => item.columnName !== "全部应用"
      );
    } catch (e) {
      ElMessage.error(isEdit.value ? "栏目更新失败" : "栏目创建失败");
    } finally {
      loading.close();
    }
  });
}

// 删除图片时清空addForm.backgroundImage
function handleAddImageRemove() {
  addForm.backgroundImage = "";
  addUploadFileList.value = [];
}

// 删除主屏栏目逻辑
async function handleDeleteColumn(row) {
  try {
    await ElMessageBox.confirm("确定要删除该栏目吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 显示删除Loading
    const loading = ElLoading.service({
      lock: true,
      text: "删除栏目中...",
      background: "rgba(0, 0, 0, 0.7)",
      zIndex: 9999,
    });

    try {
      await deleteColumnInfo(row.id);
      ElMessage.success("删除成功");
      // 刷新栏目列表
      const res = await listColumnInfo();
      tableData.value = res?.rows || res.data || [];
      // 同时更新 columnList，并过滤掉 "全部应用"
      columnList.value = (res?.rows || res.data || []).filter(
        (item) => item.columnName !== "全部应用"
      );
    } finally {
      loading.close();
    }
  } catch (e) {
    if (e !== "cancel") ElMessage.error("删除失败");
  }
}

// 切换显示状态
async function handleStatusChange(row, val) {
  const oldStatus = row.status;
  row.status = val ? 1 : 0;
  try {
    await updateColumnInfo({ id: row.id, status: row.status });
    ElMessage.success("状态更新成功");
    // 可选：刷新表格
    const res = await listColumnInfo();
    tableData.value = res?.rows || res.data || [];
    // 同时更新 columnList，并过滤掉 "全部应用"
    columnList.value = (res?.rows || res.data || []).filter(
      (item) => item.columnName !== "全部应用"
    );
  } catch (e) {
    row.status = oldStatus;
    ElMessage.error("状态更新失败");
  }
}

async function customAppApkUploadRequest(option) {
  // 显示上传Loading
  const loading = ElLoading.service({
    lock: true,
    text: "APK文件上传中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 9999,
  });

  let formData = new FormData();
  formData.append("file", option.file);
  try {
    const res = await uploadAppApk(formData);
    if (res.apk) {
      appForm.name = res.apk.name || "";
      appForm.packageName = res.apk.packageName || "";
      appForm.orderNum = res.apk.orderNum || "";
      appForm.size = res.fileSize || "";
      appForm.versionCode = res.apk.versionCode || "";
      appForm.versionName = res.apk.versionName || "";

      appForm.minsdkVersion = res.apk.minSdkVersion || "";
      appForm.targetSdkVersion = res.apk.targetSdkVersion || "";
      appForm.icon = res.apk.icon || "";
      appForm.iconFullPath = res.apk.iconFullPath || "";
    }
    appForm.url = res.url || "";
    option.onSuccess(res, option.file);
    ElMessage.success("APK文件上传成功");
  } catch (e) {
    console.log(e);
    ElMessage.error("APK文件上传失败");
    option.onError();
  } finally {
    loading.close();
  }
}

// 用栏目数据生成轮播图数据
const carouselColumns = computed(() =>
  tableData.value.filter((item) => item.status === 1)
);
function handleColumnChange(val) {
  appForm.columnId = val;
  appForm.isCommon = 0;
}
function handleDeleteApp(row) {
  ElMessageBox.confirm("确定要删除该应用吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 显示删除Loading
      const loading = ElLoading.service({
        lock: true,
        text: "删除应用中...",
        background: "rgba(0, 0, 0, 0.7)",
        zIndex: 9999,
      });

      try {
        await delBoxapp(row.id);
        ElMessage.success("删除成功");
        await getAppInfoList(currentColumnId);
      } finally {
        loading.close();
      }
    })
    .catch(() => {});
}

// 处理设置默认应用
async function handleSetDefault(row) {
  const newIsDefault = row.isDefault === 1 ? 0 : 1;
  const actionText = newIsDefault === 1 ? "设为默认" : "设为默认";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}应用"${row.name}"吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "custom-message-box",
        zIndex: 3002,
      }
    );

    // 显示设置Loading
    const loading = ElLoading.service({
      lock: true,
      text: "设置默认应用中...",
      background: "rgba(0, 0, 0, 0.7)",
      zIndex: 9999,
    });

    try {
      const formData = new URLSearchParams();
      formData.append("appId", row.id);
      formData.append("columnId", currentColumnId);
      formData.append("isDefault", newIsDefault);

      await updateDefaultApp(formData);
      ElMessage({
        message: `${actionText}成功`,
        type: "success",
        customClass: "custom-message",
        zIndex: 3003,
      });
      // 刷新应用列表
      await getAppInfoList(currentColumnId);
    } finally {
      loading.close();
    }
  } catch (e) {
    if (e !== "cancel") {
      ElMessage({
        message: `${actionText}失败`,
        type: "error",
        customClass: "custom-message",
        zIndex: 3003,
      });
    }
  }
}

function modeTypeText(val) {
  if (val === 0 || val === "0") return "标准模式";
  if (val === 1 || val === "1") return "学习模式";
  return "";
}

function toggleLogoStatus() {
  form.value.logoStatus = form.value.logoStatus === 1 ? 0 : 1;
  submitLogoStatus();
}

function formatSize(sizeInBytes) {
  if (sizeInBytes === null || sizeInBytes === undefined || sizeInBytes === "") {
    return "";
  }
  const sizeInMB = (sizeInBytes / (1024 * 1024)).toFixed(2);
  return `${sizeInMB} MB`;
}
</script>

<style scoped>
.app-container {
  padding: 40px 32px;
  min-height: 90vh;
  height: 90vh;
  background: #f7f8fa;
  box-sizing: border-box;
}
.equal-height-row {
  display: flex;
  align-items: stretch;
  height: 100%;
}
.equal-height-col {
  /* display: flex; */
  /* flex-direction: column; */
  height: 100%;
}
.fill-height {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.main-content {
  /* border: 2px solid #222; */
  border-radius: 12px;
  padding: 32px 32px 40px 32px;
  background: #fff;
  height: 55%;
  position: relative;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-bottom: 5%;
}
.logo-box {
  position: absolute;
  top: 32px;
  left: 32px;
  z-index: 10;
}
.logo-img {
  width: 80px;
  height: 80px;
}
.background-box {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  z-index: 1;
  pointer-events: none;
}
.background-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px;
}
.carousel-section {
  border-radius: 16px;
  padding: 40px 24px 32px 24px;
  margin-top: 80px;
  /* background: linear-gradient(135deg, #f0f4fa 0%, #e9eafc 100%); */
  /* box-shadow: 0 4px 24px rgba(80, 120, 200, 0.08); */
  position: relative;
  z-index: 2;
}
.carousel-card {
  width: 220px;
  height: 260px;
  border-radius: 22px;
  box-shadow: 0 8px 32px rgba(60, 80, 120, 0.18);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
  margin: 0 auto;
  position: relative;
  background: #fff;
  overflow: hidden;
  transition: box-shadow 0.2s, transform 0.2s;
}
.carousel-card:hover {
  box-shadow: 0 16px 48px rgba(60, 80, 120, 0.28);
  transform: scale(1.04);
  z-index: 2;
}
.card-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  left: 0;
  top: 0;
  border-radius: 22px;
  z-index: 1;
}
.card-title {
  color: #fff;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  letter-spacing: 2px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  padding: 14px 0 14px 0;
  background: linear-gradient(
    0deg,
    rgba(30, 40, 60, 0.85) 90%,
    rgba(30, 40, 60, 0.01) 100%
  );
  border-bottom-left-radius: 22px;
  border-bottom-right-radius: 22px;
  z-index: 2;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
}
.carousel-card::after {
  display: none;
}
.sidebar {
  border-radius: 16px;
  background: #fff;
  padding: 0;
  height: 100%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.07);
  display: flex;
  flex-direction: column;
  gap: 0;
  font-family: "Segoe UI", "PingFang SC", "Hiragino Sans", Arial, sans-serif;
}
.sidebar-card {
  padding: 20px 0;
}
.sidebar-section {
  background: #fafbfc;
  border-radius: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  padding: 18px 16px 14px 16px;
  margin: 0 14px;
  margin-bottom: 14px;
}
.sidebar-section-form {
  margin-bottom: 10px;
}
.sidebar-section-table {
  margin-bottom: 0;
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
}
.upload-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 0;
}

.upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.upload-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  text-align: center;
}
.logo-upload-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
}
.logo-preview1 {
  width: 80px;
  height: 80px;
  display: block;
  margin-bottom: 8px;
  border-radius: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  object-fit: cover;
  border: 1.5px solid #e0e7ef;
}
.logo-preview2 {
  width: 200px;
  display: block;
  margin-bottom: 8px;
  border-radius: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  object-fit: cover;
  border: 1.5px solid #e0e7ef;
}
.submit-btn {
  width: 100%;
  border-radius: 18px;
  font-weight: 500;
  letter-spacing: 2px;
  font-size: 12px;
  padding: 8px 16px;
}
.button-group {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
  margin-top: 8px;
}
.table-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.table-header-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.add-btn,
.submit-btn,
.el-button--success {
  background: linear-gradient(90deg, #5a9cf8 0%, #6ec1e4 100%);
  color: #fff !important;
  border: none;
  border-radius: 18px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(80, 120, 200, 0.1);
  transition: background 0.2s, box-shadow 0.2s;
}
.add-btn:hover,
.submit-btn:hover,
.el-button--success:hover {
  background: linear-gradient(90deg, #6ec1e4 0%, #5a9cf8 100%);
  box-shadow: 0 4px 16px rgba(80, 120, 200, 0.18);
}
.sidebar-table {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 0;
  width: 100%;
  min-width: 0;
  flex: 1 1 0;
  min-height: 0;
}

/* 确保表格可以水平滚动 */
.sidebar-table .el-table__body-wrapper {
  overflow-x: auto;
}

.sidebar-table .el-table__header-wrapper {
  overflow-x: auto;
}

/* 表格容器样式 */
.table-container {
  width: 100%;
  overflow-x: auto;
  border-radius: 8px;
}
.table-img {
  width: 64px;
  height: 64px;
  border-radius: 6px;
  object-fit: cover;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  border: 1px solid #e0e7ef;
  background: #f4f6fa;
}
.app-table-section {
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
}
/* 修复 el-image 遮罩层被覆盖问题 */
:global(.el-overlay) {
  /* z-index: 3000 !important; */
}

/* 确保loading弹窗在最上层 */
:global(.el-loading-mask) {
  z-index: 9999 !important;
}

:global(.el-loading-spinner) {
  z-index: 10000 !important;
}

/* 确保消息弹窗在最上层 */
:global(.custom-message) {
  z-index: 30011111 !important;
}

:global(.custom-message-box) {
  z-index: 3002 !important;
}

/* 确保所有消息弹窗都在最上层 */
:global(.el-message) {
  z-index: 30011111 !important;
}

:global(.el-message-box) {
  z-index: 3002 !important;
}
:deep(.el-carousel__mask) {
  background: none;
}
:deep(.el-select__popper) {
  z-index: 30011111 !important;
}
:deep(.el-loading-mask) {
  z-index: 30011111 !important;
}

/* 专门为应用选择下拉框设置层级 */
:deep(.app-select-dropdown) {
  z-index: 999999 !important;
}

/* 确保所有下拉框都在最上层 */
:deep(.el-select-dropdown) {
  z-index: 999999 !important;
}

/* 修复可能的定位问题 */
:deep(.el-select__popper) {
  position: absolute !important;
  z-index: 999999 !important;
}

/* 确保弹窗内的下拉框层级正确 */
.el-dialog :deep(.el-select__popper) {
  z-index: 999999 !important;
}

.el-dialog :deep(.el-select-dropdown) {
  z-index: 999999 !important;
}

/* 全局修复Element UI下拉框层级问题 */
:global(.el-select-dropdown) {
  z-index: 999999 !important;
}

:global(.el-select__popper) {
  z-index: 999999 !important;
}

/* 确保下拉框在弹窗中正确显示 */
:global(.el-dialog__wrapper) {
  z-index: 9998 !important;
}

/* 修复可能的overflow问题 */
:global(.el-dialog__body) {
  overflow: visible !important;
}

:global(.el-form-item) {
  overflow: visible !important;
}
</style>
